import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
//这个文件的作用是 配置整个应用的页面路由和访问权限控制逻辑，
// 决定了用户能访问哪些页面、如何跳转以及是否需要登录等行为。
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: () => import('../views/Login/MyLogin.vue'),
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../views/Home/MyHome.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'HomePage',
          component: () => import('../views/Home/HomePage.vue')
        },
        {
          path: 'page1',
          name: 'Page1',
          component: () => import('../views/Page1.vue')
        },
        {
          path: 'page2',
          name: 'Page2',
          component: () => import('../views/Page2.vue')
        },
        {
          path: 'page3',
          name: 'Page3',
          component: () => import('../views/Page3.vue')
        },
        {
          path: 'page4',
          name: 'Page4',
          component: () => import('../views/Page4.vue')
        },
        {
          path: 'page5',
          name: 'Page5',
          component: () => import('../views/Page5.vue')
        },
        {
          path: 'page6',
          name: 'Page6',
          component: () => import('../views/Page6.vue')
        }
      ]
    }
  ],
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isLoggedIn) {
      ElMessage.warning('请先登录')
      next('/')
    } else {
      next()
    }
  } else {
    if (isLoggedIn && to.path === '/') {
      next('/home')
    } else {
      next()
    }
  }
})

export default router
